package com.zhang.admin.controller;

import com.zhang.admin.bean.User;
import com.zhang.admin.bean.UserRole;
import com.zhang.admin.service.UserRoleService;
import com.zhang.admin.service.UserService;
import com.zhang.admin.util.MD5;
import com.zhang.util.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @title: 用户控制器
 * @author: zhangyf
 * @date: 2023/3/29 13:54
 **/
@RestController // 控制器实现了rest api
@RequestMapping("/admin/user")
public class UserController {

    // 获取所有用户
    @GetMapping("getAllUsers")
    public Result<List<User>> getAllUsers(){
        return Result.of(200,"success", UserService.getAllUsers());
    }

    // 根据用户id获取用户信息
    @GetMapping("getUser/{userId}")
    public Result<User> getUserById(@PathVariable Long userId){
        return Result.of(200,"success",UserService.getUserById(userId));
    }

    // 添加用户
    @PostMapping("addUser")
    public Result<String> addUser(@RequestBody User userInfo){
        UserService.addUser(
                userInfo.getUsername(),
                MD5.encrypt(userInfo.getPassword())
        );
        return Result.of(200,"success","添加用户成功");
    }

    // 删除用户
    @DeleteMapping("deleteUser/{userId}")
    public Result<String> deleteUser(@PathVariable Long userId){
        UserService.deleteUserById(userId);
        return Result.of(200,"success","删除一个用户");
    }

    // 根据用户id获取角色id
    @GetMapping("getRoleIdByUserId/{userId}")
    public Result<Long> getRoleIdByUserId(@PathVariable Long userId){
        return Result.of(200,"success", UserRoleService.getRoleIdByUserId(userId));
    }

    // 为用户分配角色
    @PostMapping("assignRoleToUser")
    public Result<String> assignRoleToUser(@RequestBody UserRole userRole){
        UserRoleService.addUserIdRoleIdRelationship(userRole.getUserId(),userRole.getRoleId());
        return Result.of(200,"success","分配角色成功");
    }




}
